﻿using System;
using Autofac;
using Autofac.Core;

namespace ReactiveGraph.Core.Configuration.Containers
{
    public class AutofacCoreModule : Module
    {
        private readonly NodeNameService _nodeNameService = new NodeNameService();

        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterInstance(_nodeNameService).AsSelf();
            builder.Register<Func<IReactiveNode, string>>(context => (node => _nodeNameService.GetName(node)));
            builder.Register((c, p) => new ReactiveNode(_nodeNameService.GetName, c.Resolve<ReactiveNodeList>()))
                .As<IReactiveNode>()
                .As<ReactiveNode>();
                
            builder.RegisterType<ReactiveNodeList>();
        }
    }

    public class NodeNameService
    {
        private int _id = 1;
        private string _override;

        public string GetName(IReactiveNode node)
        {
            if (_override != null)
                return _override;
            return
                node.GetType().Name + _id++;
        }

        public void OverrideName(string name)
        {
            _override = name;
        }

        public void ClearOverride()
        {
            _override = null;
        }
    }
}
